package com.geline.easyexcel.handler;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.geline.easyexcel.domain.ExcelError;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;

import java.util.List;
import java.util.Map;

/**
 * 单元格批注处理器
 *
 * @author: mengxin
 * @date: 2024/1/15 9:27
 */
@Slf4j
public class CommentWriteHandler implements RowWriteHandler {

    private Map<String, List<ExcelError>> excelErrorMap;

    public CommentWriteHandler(Map<String, List<ExcelError>> excelErrorMap) {
        this.excelErrorMap = excelErrorMap;
    }

    @Override
    public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
                                Integer relativeRowIndex, Boolean isHead) {
        for(String rowIndex : excelErrorMap.keySet()){
            List<ExcelError> list = excelErrorMap.get(rowIndex);
            if(CollUtil.isNotEmpty(list)){
                Sheet sheet = writeSheetHolder.getSheet();
                Drawing<?> patriarch = sheet.createDrawingPatriarch();
                Row currRow = sheet.getRow(Integer.valueOf(rowIndex));
                for (ExcelError excelError : list) {
                    writeCellComment(patriarch, currRow, excelError);
                    fillForegroundColor(writeSheetHolder.getParentWriteWorkbookHolder().getWorkbook(), currRow, excelError.getColIndex());
                }
            }
        }
    }

    private void writeCellComment(Drawing<?> patriarch, Row row, ExcelError excelError){
        // 在第rowIndex行 第colIndex列创建一个批注
        int colIndex = excelError.getColIndex();
        int rowIndex = excelError.getRowIndex();
        XSSFClientAnchor clientAnchor = new XSSFClientAnchor(0, 0, 0, 0, colIndex, rowIndex, colIndex+2, rowIndex+2);
        Comment comment = patriarch.createCellComment(clientAnchor);
        comment.setString(new XSSFRichTextString(excelError.getMsg()));
        Cell cell = row.getCell(colIndex);
        if(cell != null){
            cell.setCellComment(comment);
        }else {
            Cell newCell = row.createCell(colIndex);
            newCell.setCellComment(comment);
        }
    }

    private void fillForegroundColor(Workbook workbook, Row row, Integer columnIndex){
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Cell cell = row.getCell(columnIndex);
        if(cell!=null){
            cell.setCellStyle(cellStyle);
        }
    }
}
